﻿using Common.Data;
using CoreApi.Meta;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Transactions;
using Common.Object;
using System;
using System.Data.Common;

namespace CoreApi.Impl
{
    public class PropertyManagerService:IPropertyManagerService
    {
        private string _conName = "pm";

        public PropertyManagerService()
        {
            this._conName = ConfigurationManager.AppSettings["pm.connectionStringName"] ?? _conName;
        }        

        public ReturnValue CheckRegisterMobile(string registerMobile)
        {
            Database db = DatabaseFactory.CreateDatabase(this._conName);
            DbFilter[] filters=new DbFilter[]{
                new DbFilter("a.RegMobile",registerMobile)
            };
            int cnt=DbHelper.ExecuteScalar(db, null, SQL.PropertyManagerService.PropertyRegisterMobile, filters);
            if (cnt == 0) return new ReturnValue(false, ErrorMessage.PropertyManagerService.NotFound);
            else return new ReturnValue();
        }
        public ReturnValue BindWechat(string registerMobile, string wechatUnionId)
        {
            Database db = DatabaseFactory.CreateDatabase(this._conName);
            DbFilter[] filters = new DbFilter[]{
                new DbFilter("RegMobile",registerMobile)
                ,new DbFilter("Status",Status.Active)
                ,new DbFilter("WechatUnionId",string.Empty)
            };
            DbColumn[] columns = new DbColumn[]{
                new DbColumn("WechatUnionId",wechatUnionId)
                ,new DbColumn("BindTime",DbType.DateTime,DateTime.Now)
            };
            int cnt = DbHelper.ExecuteUpdate(db, null, SQL.TABLE.PROPERTYMANAGER,columns, filters);
            if (cnt<=0) return new ReturnValue(false, ErrorMessage.PropertyManagerService.BindWechatFailed);
            else return new ReturnValue();
        }
        public ReturnValue WechatServiceSheetList(string wechatUnionId, string status, string timeRange)
        {
            Database db = DatabaseFactory.CreateDatabase(this._conName);
            IDictionary prop = DbHelper.ExecuteSingle(db, null, SQL.TABLE.PROPERTYMANAGER, "ManagerId,Status".BuildDbColumnArray(), new DbFilter[] { new DbFilter("WechatUnionId", wechatUnionId) });
            if (prop == null) return new ReturnValue(false, ErrorMessage.PropertyManagerService.NotFound);
            if (!Status.Active.Equals(prop["STATUS"])) return new ReturnValue(false, ErrorMessage.PropertyManagerService.StatusError);
            List<DbFilter> filters = new List<DbFilter>();
            filters.Add(new DbFilter("a.ManagerId", prop["MANAGERID"].ToString()));
            if (status!=null && !status.Equals("*")) filters.Add(new DbFilter("a.Status", status));
            if (timeRange != null && !timeRange.Equals(string.Empty)) filters.Add(new DbFilter("a.CreateTime", DbType.DateTime, timeRange.Split(';')));
            DataTable datas = DbHelper.ExecuteDataTable(db, null, SQL.PropertyManagerService.GetServiceSheet, filters.ToArray(), "a.CreateTime desc");
            return new ReturnValue(datas);
        }
        public ReturnValue WechatServiceSheetOptList(string wechatUnionId, int serviceSheetId)
        {
            Database db = DatabaseFactory.CreateDatabase(this._conName);
            IDictionary prop = DbHelper.ExecuteSingle(db, null, SQL.TABLE.PROPERTYMANAGER, "ManagerId,Status".BuildDbColumnArray(), new DbFilter[] { new DbFilter("WechatUnionId", wechatUnionId) });
            if (prop == null) return new ReturnValue(false, ErrorMessage.PropertyManagerService.NotFound);
            if (!Status.Active.Equals(prop["STATUS"])) return new ReturnValue(false, ErrorMessage.PropertyManagerService.StatusError);
            DbFilter[] filters = new DbFilter[]{
                new DbFilter("c.WechatUnionId",wechatUnionId)
                ,new DbFilter("a.ServiceSheetId",DbType.Int32,serviceSheetId)
            };
            DataTable datas = DbHelper.ExecuteDataTable(db, null, SQL.PropertyManagerService.GetServiceSheetOpt, filters, "a.OptTime desc");
            return new ReturnValue(datas);
        }
        private ReturnValue GetServiceSheet(Database db, DbTransaction trans,string wechatUnionId,int serviceSheetId)
        {
            IDictionary prop = DbHelper.ExecuteSingle(db, null, SQL.TABLE.PROPERTYMANAGER, "ManagerId,Status".BuildDbColumnArray(), new DbFilter[] { new DbFilter("WechatUnionId", wechatUnionId) });
            if (prop == null) return new ReturnValue(false, ErrorMessage.PropertyManagerService.NotFound);
            if (!Status.Active.Equals(prop["STATUS"])) return new ReturnValue(false, ErrorMessage.PropertyManagerService.StatusError);
            DbFilter[] filters = new DbFilter[]{
                new DbFilter("e.WechatUnionId",wechatUnionId)
                ,new DbFilter("a.ServiceSheetId",DbType.Int32,serviceSheetId)
            };
            IDictionary data = DbHelper.ExecuteSingle(db, trans, SQL.PropertyManagerService.GetServiceSheet, filters);
            if (data == null) return new ReturnValue(false, ErrorMessage.PropertyManagerService.ServiceSheetNotFound);
            return new ReturnValue(data);
        }
        public ReturnValue WechatServiceSheetInfo(string wechatUnionId, int serviceSheetId)
        {
            Database db = DatabaseFactory.CreateDatabase(this._conName);
            ReturnValue dt = GetServiceSheet(db, null, wechatUnionId, serviceSheetId);
            if (dt.Passed) return new ReturnValue(true, (dt.Data as IDictionary).ToJsonString());
            else return new ReturnValue(false, dt.Data);
        }
        public ReturnValue WechatServiceSheetOptResult(string wechatUnionId, int serviceSheetId, string optResult, string comments)
        {
            Database db = DatabaseFactory.CreateDatabase(this._conName);
            using (TransactionScope tx = new TransactionScope())
            {
                IDictionary prop = DbHelper.ExecuteSingle(db, null, SQL.TABLE.PROPERTYMANAGER, "ManagerId,RegRealName,Status".BuildDbColumnArray(), new DbFilter[] { new DbFilter("WechatUnionId", wechatUnionId) });
                if (prop == null) return new ReturnValue(false, ErrorMessage.PropertyManagerService.NotFound);
                if (!Status.Active.Equals(prop["STATUS"])) return new ReturnValue(false, ErrorMessage.PropertyManagerService.StatusError);
                string optName = prop["REGREALNAME"].ToString();
                ReturnValue rv = GetServiceSheet(db, null, wechatUnionId, serviceSheetId);
                if (!rv.Passed) return rv;
                string sheetStatus = (rv.Data as IDictionary)["STATUS"].ToString();
                if (!ServiceSheetStatus.Open.Equals(sheetStatus)) return new ReturnValue(false, ErrorMessage.PropertyManagerService.ServiceSheetStatusClosed);
                if (ServiceSheetOptResult.Done.Equals(optResult) || ServiceSheetOptResult.Misinformation.Equals(optResult))
                {
                    DbColumn[] closeColumns = new DbColumn[]{
                        new DbColumn("ClosedBy",optName)
                        ,new DbColumn("ClosedTime",DbType.DateTime,DateTime.Now)
                        ,new DbColumn("Status",ServiceSheetStatus.Closed)
                    };
                    DbFilter[] filters = new DbFilter[]{
                        new DbFilter("ServiceSheetId",DbType.Int32,serviceSheetId)
                    };
                    DbHelper.ExecuteUpdate(db, null,SQL.TABLE.SERVICESHEET,closeColumns, filters);
                }
                DbColumn[] insertColumn = new DbColumn[]{
                    new DbColumn("ServiceSheetId",DbType.Int32,serviceSheetId)
                    ,new DbColumn("OptResult",optResult)
                    ,new DbColumn("Comments",comments)
                    ,new DbColumn("OptName",optName)
                    ,new DbColumn("OptTime",DbType.DateTime,DateTime.Now)
                };
                DbHelper.ExecuteInsert(db, null, SQL.TABLE.SERVICESHEETOPT, insertColumn);
                tx.Complete();
                return new ReturnValue();
            }
        }
    }
}
